<?php

include_once '../model/Comentario.php';
include_once '../model/Avance.php';
include_once '../model/Usuario.php';
include_once '../daos/AvanceDao.php';
include_once '../daos/ComentarioDao.php';
include_once '../reports/ReportsManager.php';
include_once '../commons/Constants.php';

class ComentariosController {

    public function __construct() {
        
    }

    public function listar() {

        session_start();

        $idAvance = $_POST['id'];
        $msj = "Ha ocurrido un error, por favor intente más tarde.";

        try {
            $rm = new ReportsManager();

            $path = session_id() . ".pdf";
            $rm->generarReporteAvance("tmp\\" . $path, $idAvance);
            $_SESSION["pdf"] = "../tmp/" . $path;
            $_SESSION["idAvance"] = $_POST['id'];

            $dao = new ComentarioDao();
            $listComentarios = $dao->getComentariosByAvance($_POST['id']);
            $_SESSION["listComentarios"] = serialize($listComentarios);

            $ok = $dao->getEstatusByAvance($_POST['id'], "S");
            $total = count($listComentarios);
            $notok = $total - $ok;

            $_SESSION["ok"] = ($ok * 100) / $total;
            $_SESSION["notok"] = ($notok * 100) / $total;

            $msj = "";
        } catch (Exception $e) {
            
        }
        $_SESSION['msj'] = $msj;
        return "../views/comentarios.php";
    }

    public function add() {

        session_start();

        $responce = array('msj' => "Error consultando la obra", 'estatus' => AJAX_ERROR);

        try {

            $aDao = new AvanceDao();
            $avance = $aDao->getAvanceById($_SESSION["idAvance"]);

            $usuario = new Usuario();
            $usuario = unserialize($_SESSION['usuario']);

            $comentario = new Comentario();
            $comentario->setComentario($_POST["commentAdd"]);
            $comentario->setFecha(date('Y-m-d'));
            $comentario->setConforme($_POST["ok"]);
            $comentario->setAvance($avance);
            $comentario->setUsuario($usuario);

            $dao = new ComentarioDao();
            $comentario = $dao->saveComent($comentario);

            if (isset($comentario)) {
                
                $listComentarios = $dao->getComentariosByAvance($_SESSION["idAvance"]);

                $ok = $dao->getEstatusByAvance($_SESSION["idAvance"], "S");
                $total = count($listComentarios);
                $notok = $total - $ok;

                $responce = array('msj' => "",
                    'estatus' => AJAX_SUCCESSFUL,
                    'ok' => ($ok * 100) / $total,
                    'notok' => ($notok * 100) / $total);
            }
        } catch (Exception $e) {
            
        }

        return json_encode($responce);
    }

}

?>